package net.ib.mtalk.network.task;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Session.GetUserProfileReq;
import net.ib.mntalk.protocol.Session.GetUserProfileRes;
import net.ib.mtalk.R;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.network.MethodId.Session;
import net.ib.mtalk.network.TcpEnvelope;
import net.ib.mtalk.ui.setting.user.UserActivity;
import net.ib.mtalk.util.MTalkLogWriter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class GetUserProfilesTask extends AsyncNetTask {
	
	private GetUserProfileReq getUserProfileReq;

	public GetUserProfilesTask(Context _context, Handler _uiHandler, GetUserProfileReq getUserProfileReq) {
		super(_context, _uiHandler);
		mContext = _context;
		mUiHandler = _uiHandler;
		this.getUserProfileReq = getUserProfileReq;
	}

	@Override
	protected TcpEnvelope onPreExecute() {
		TcpEnvelope rev = new TcpEnvelope.Builder()
			.setType(TcpEnvelope.REQUEST)
			.setMessage(getUserProfileReq)
			.setMethodId(Session.User.GetUserProfile)
			.build();
		return rev;
	}

	@Override
	protected void onPostExecute(int resultCode, Object sentObject,
			Object receivedObject) {
		MTalkLogWriter.d("GetUserProfilesTask.onPostExecute() resultCode : " + resultCode);
		if (receivedObject == null) {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_UNKNOWN_ERROR));
			return;
		}
		
		TcpEnvelope resultEnvelope = (TcpEnvelope) receivedObject;
		GetUserProfileRes getUserProfileRes = (GetUserProfileRes) resultEnvelope.getMessage();
		
		MTalkLogWriter.d("GetUserProfilesTask ResponseCode : " + getUserProfileRes.getResponseCode());
		
		if(getUserProfileRes.getResponseCode() == Common.SUCCESS){
			GlobalPreferences.setUserName(getUserProfileRes.getProfile().getName().getDisplayName());
			GlobalPreferences.setUserStatus(getUserProfileRes.getProfile().getStatus());
			GlobalPreferences.setUserBirthday(getUserProfileRes.getProfile().getBirthday());
			
			Message msg = mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_GET_USER_PROFILE_SUCCESS);
			msg.obj = getUserProfileRes.getProfile();
			mUiHandler.sendMessageAtFrontOfQueue(msg);
		} else {
			mUiHandler.sendMessageAtFrontOfQueue(mUiHandler.obtainMessage(HandlerMsgConst.HANDLER_GET_USER_PROFILE_FAIL));
		}
	}

}
